package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.domain.dto.request.LoginRequest;
import com.example.domain.dto.request.RegisterRequest;
import com.example.domain.dto.result.ApiResponse;
import com.example.domain.dto.result.PersonResult;
import com.example.domain.entity.Person;
import com.example.factory.ResultFactory;
import com.example.service.impl.PersonServiceImpl;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import java.util.Random;
import org.springframework.web.client.RestTemplate;
import io.swagger.v3.oas.annotations.Operation;

@CrossOrigin
@RestController
@RequestMapping("/account")
@Tag(name="账号管理器", description = "管理账号的注册登录等")
public class AccountController {
    @Autowired
    private PersonServiceImpl personService;

    @Autowired
    private ResultFactory resultFactory;

    private Map<String, String> codeMap = new HashMap<>();

    private RestTemplate restTemplate = new RestTemplate();

    @PostMapping("/register")
    @Operation(summary = "注册")
    public ApiResponse<Person> register(@RequestBody RegisterRequest request) {

        // 验证验证码
        String storedCode = codeMap.get(request.getPhone());
        if (storedCode == null || !storedCode.equals(request.getCode())) {
            return ApiResponse.error("验证码错误或已过期");
        }
        // 验证成功后移除验证码，避免重复使用
        codeMap.remove(request.getPhone());

        try {
            Person person = personService.register(request);
            return ApiResponse.success("注册成功", person);
        } catch (RuntimeException e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    @PostMapping("/login")
    @Operation(summary = "登录")
    public ApiResponse<PersonResult> login(@RequestBody LoginRequest request) {
        if(request.getWay().equals("验证码")) {
            // 验证验证码
            String storedCode = codeMap.get(request.getIdentifier());
            if (storedCode == null || !storedCode.equals(request.getCode())) {
                return ApiResponse.error("验证码错误或已过期");
            }
            // 验证成功后移除验证码，避免重复使用
            codeMap.remove(request.getIdentifier());
            Person person = this.personService.getByPhone(request.getIdentifier());
            if(person == null) {
                return ApiResponse.error("用户不存在");
            }
            PersonResult personResult = this.resultFactory.convert(person);
            return ApiResponse.success("登录成功", personResult);
        }


        try {
            Person person = personService.login(request);
            PersonResult personResult = this.resultFactory.convert(person);
            return ApiResponse.success("登录成功", personResult);
        } catch (RuntimeException e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    @GetMapping("/getCode")
    @Operation(summary = "获取验证码")
    public ApiResponse<String> getCode(String phone) {
        // 生成四位随机验证码
        Random random = new Random();
        String code = String.format("%04d", random.nextInt(10000));

        // 将验证码存入codeMap，键为手机号
        codeMap.put(phone, code);

        // 调用外部接口发送短信
        String url = "https://push.spug.cc/send/XALgM8MD3zrdnwDe?code=" + code + "&targets=" + phone;
        try {
            restTemplate.getForObject(url, String.class);
            return ApiResponse.success("验证码发送成功");
        } catch (Exception e) {
            // 发送失败时移除验证码
            codeMap.remove(phone);
            return ApiResponse.error("验证码发送失败: " + e.getMessage());
        }
    }

    @GetMapping("/updatePassword")
    @Operation(summary = "修改密码")
    public ApiResponse<String> updatePassword(String phone, String newPassword, String code) {
        // 验证验证码
        String storedCode = codeMap.get(phone);
        if (storedCode == null || !storedCode.equals(code)) {
            return ApiResponse.error("验证码错误或已过期");
        }
        // 验证成功后移除验证码，避免重复使用
        codeMap.remove(phone);

        // 检查手机号和新密码是否提供
        if (phone == null || newPassword == null) {
            return ApiResponse.error("手机号和新密码不能为空");
        }

        boolean success = personService.updatePassword(phone, newPassword);

        if (success) {
            return ApiResponse.success("密码修改成功");
        } else {
            return ApiResponse.error("密码修改失败，用户不存在");
        }
    }
}
